<?php

namespace app\admin\controller\crm;

use app\admin\controller\Auth;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use Throwable;

/**
 * @ControllerAnnotation(title="crm_record")
 */
class Record extends AdminController
{


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\CrmRecord();

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParamesScop();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                //替换
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $list[$key] = $value;
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $typeList=Db::name('crm_record_type')->field('`name`')->where('status','=',1)->order('sort ASC')->column('name','name');
        $this->assignconfig('record_type',$typeList);
        return $this->fetch();
    }

    /**
     * view
     * 查看客户信息
     *
     * @access public
     * @author liuqi
     * @return void
     */
    public function view(){
        $id=Request::param('id',0,'intval');
        $result = Db::table('crm_customer')->where(['id'=>$id])->find();
        if (empty($result)){
            $this->error('不存在的客户信息！');
        }
        $record= Db::table('crm_record')->alias('r')->field('r.*,a.avatar')->join('admin a','r.admin_id = a.admin_id')->where(['r.customer_id'=>$id])->order('id DESC')->limit(10)->select()->toArray();
        if($record){
            array_multisort(array_column($record,'id'),SORT_ASC,$record);
            $result['record']=$record;
        }else{
            $result['record']=[];
        }

        // 是否有查看手机号的权限
        if ($this->admin['isphone'] == 0) {
            $result['phone'] = mb_substr($result['phone'], 0, 3).'****'. mb_substr($result['phone'], 7, 11);
        }
        $fields=Db::query('SELECT `editinput` FROM `system_field` WHERE (`edit`=1 AND `table`="crm_customer" AND `editinput` is not null) OR `field`="pr_user" OR `field`="at_user" OR `field`="last_up_time" OR `field`="last_up_records" OR `field`="at_user" OR `field`="create_time" order BY `sort` ASC,id ASC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=trim($v['editinput']);
        }
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display($fields_str,['row'=>$result]);
        $this->assign('fields_str', $fields_str);
        $this->assign('result',$result);
        $this->app->view->engine()->layout($this->layout);
        return $this->fetch();
    }

    /**
     * dialogue
     * 写跟进
     *
     * @access public
     * @author liuqi
     * @return void
     */
    public function dialogue(){
        $id=Request::param('id',0,'intval');
        $result = Db::table('crm_customer')->where(['id'=>$id])->find();
        if (empty($result)){
            $this->error('不存在的客户信息！');
        }
        $record= Db::table('crm_record')->alias('r')->field('r.*,a.avatar')->join('admin a','r.admin_id = a.admin_id')->where(['r.customer_id'=>$id])->order('id DESC')->limit(10)->select()->toArray();
        if($record){
            array_multisort(array_column($record,'id'),SORT_DESC,$record);
            $result['record']=$record;
        }else{
            $result['record']=[];
        }

        /*foreach ($result['comment'] as $k => $v){
            $result['comment'][$k]['reply'] = Db::table('crm_reply')->where(['comment_id'=>$v['id']])->select();
        }*/
        // 是否有查看手机号的权限
        if ($this->admin['isphone'] == 0) {
            $result['phone'] = mb_substr($result['phone'], 0, 3).'****'. mb_substr($result['phone'], 7, 11);
        }
        $fields=Db::query('SELECT `editinput` FROM `system_field` WHERE (`edit`=1 AND `table`="crm_customer" AND `editinput` is not null) OR `field`="pr_user" OR `field`="at_user" OR `field`="last_up_time" OR `field`="last_up_records" OR `field`="at_user" OR `field`="create_time" order BY `sort` ASC,id ASC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str.=trim($v['editinput']);
        }
        $this->app->view->engine()->layout(false);
        $fields_str=$this->display($fields_str,['row'=>$result]);
        $this->assign('fields_str', $fields_str);
        $this->assign('result',$result);
        $this->app->view->engine()->layout($this->layout);
        return $this->fetch();
    }

    public function add()
    {
        if($this->request->post()){

            $data['customer_id'] = Request::param('customer_id');
            if(empty($data['customer_id'])){
                return json(['code'=>0,'msg'=>'请求参数非法!']);
            }

            $customer_row = Db::table('crm_customer')
                ->field('`name`,`phone`')
                ->where(['id'=>$data['customer_id'], 'pr_user' => $this->admin['username']])
                ->find();
            if(empty($customer_row)){
                return json(['code'=>0,'msg'=>'不存在的客户!']);
            }

            $data['admin_id'] = $this->admin['admin_id'];
            $data['khname'] = $customer_row['name'];
            $data['khphone'] = $customer_row['phone'];
            $data['pr_user'] = $this->admin['username'];
            $data['content'] = Request::param('content');
            if(!$data['content']){
                return json(['code'=>0,'msg'=>'请填写跟进信息!']);
            }
            $data['money'] = Request::param('money');
            $data['time'] = Request::param('time');
            $data['need_files'] = Request::param('need_files');
            $data['record_files'] = Request::param('record_files');
            $data['record_type'] = Request::param('record_type','','trim');
            if(!$data['record_type']){
                return json(['code'=>0,'msg'=>'最少选择一种跟进类型!']);
            }
            $data['record_type'] = join(',',$data['record_type']);
            $data['create_time'] = time();

            //更新跟进记录
            $genjin['last_up_records'] = $data['content'];
            $genjin['last_up_time'] = $data['create_time'];
            if($data['money'] > 0){
                $genjin['predict_time'] = $data['time'];
                $genjin['predict_money'] = $data['money'];
            }
            $next_time = Request::param('next_up_time');
            $data['next_up_time'] = $genjin['next_up_time'] = $next_time ? strtotime($next_time) : 0;

            # 更新跟进记录
            Db::startTrans();
            try{

                # 主键锁表
                $customer = Db::table('crm_customer')
                    ->lock(true)
                    ->field('id')
                    ->where(['id'=>$data['customer_id']])
                    ->find();
                if(!$customer){
                    throw new Exception("不存在的客户");
                }

                # 新增跟进记录
                $result = Db::table('crm_record')
                    ->insert($data);
                if(!$result){
                    throw new Exception("新增跟进记录失败");
                }

                # 更新客户信息
                $update = Db::table('crm_customer')
                    ->where(['id'=>$data['customer_id']])
                    ->update($genjin);
                if($update === false){
                    throw new Exception("更新客户信息失败");
                }

                Db::commit();
            }catch (Throwable $exception){
                Db::rollback();
                return json(['code'=>0,'msg'=>$exception->getMessage()]);
            }

            $data['create_time'] = date("Y年m月d日 H:i",$data['create_time']);
            return json(['code'=> 1,'msg'=>'跟进记录成功！','data'=>$data]);


//            Db::table('crm_customer')->where(['id'=>$data['customer_id']])->update($genjin);
//
//            $result = Db::table('crm_record')->insert($data);
//            $data['create_time'] = date("Y年m月d日 H:i",$data['create_time']);
//
//            if ($result){
//                return json(['code'=> 1,'msg'=>'跟进记录成功！','data'=>$data]);
//            }else{
//                return json(['code'=>0,'msg'=>'跟进记录失败!']);
//            }
        }
    }




}
